#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <strings.h>

class InetAddr
{
private:
    void HostToNet()
    {
        bzero(&_addr, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &(_addr.sin_addr.s_addr));
    }
    void NetToHost()
    {
        _port = ntohs(_addr.sin_port);
        char buffer[64];
        inet_ntop(AF_INET, &(_addr.sin_addr.s_addr), buffer, sizeof(buffer));
    }

public:
    InetAddr() {}
    InetAddr(uint16_t port, std::string ip = "0.0.0.0")
        : _port(port), _ip(ip)
    {
        HostToNet();
    }
    InetAddr(struct sockaddr_in addr)
        : _addr(addr)
    {
        NetToHost();
    }
    void Init(struct sockaddr_in addr)
    {
        _addr=addr;
        NetToHost();
    }
    struct sockaddr*Addr()
    {
        return (struct sockaddr*)&_addr;
    }
    socklen_t Len()
    {
        return sizeof(_addr);
    }
    std::string ToString()
    {
        return _ip+"-"+std::to_string(_port);
    }
    std::string IP()
    {
        return _ip;
    }
    uint16_t Port()
    {
        return _port;
    }
    ~InetAddr() {}

private:
    uint16_t _port;
    std::string _ip;
    struct sockaddr_in _addr;
};